﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;
using DevExpress.Persistent.BaseImpl;
using DevExpress.Data.Filtering;

namespace Liekhus.TimeTracker.Module.Web.Providers
{
    public class XpoMembershipProvider : MembershipProvider
    {
        public override string ApplicationName
        {
            get { return "XpoMembershipProvider"; }
            set { }
        }

        public override string GetUserNameByEmail(string email)
        {
            return string.Empty;
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            using (Session session = XpoConnectionHelper.GetSession<User>())
            {
                session.BeginTransaction();
                try
                {
                    User user = new User(session);
                    user.UserName = username;
                    user.Email = email;
                    user.SetPassword(password);
                    user.Save();

                    session.CommitTransaction();

                    status = MembershipCreateStatus.Success;

                    return LoadMember(user);
                }
                catch
                {
                    status = MembershipCreateStatus.ProviderError;
                    session.RollbackTransaction();
                    throw;
                }
            }
        }

        private MembershipUser LoadMember(User user)
        {
            MembershipUser member = null;
            if (user != null)
            {
                member = new MembershipUser(
                                        this.Name,
                                        user.UserName,
                                        user.Oid,
                                        user.Email,
                                        string.Empty,
                                        string.Empty,
                                        user.IsActive,
                                        false,
                                        DateTime.Now,
                                        DateTime.Now,
                                        DateTime.Now,
                                        DateTime.Now,
                                        DateTime.MinValue);
            }

            return member;
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return LoadMember(LoadUser(providerUserKey));
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return LoadMember(LoadUser(username));
        }

        private User LoadUser(object providerUserKey)
        {
            using (Session session = XpoConnectionHelper.GetSession<User>())
            {
                {
                    return session.FindObject<User>(new BinaryOperator("Oid", providerUserKey));
                }
            }
        }

        private User LoadUser(string username)
        {
            using (Session session = XpoConnectionHelper.GetSession<User>())
            {
                {
                    return session.FindObject<User>(new BinaryOperator("UserName", username));
                }
            }
        }

        public override bool ValidateUser(string username, string password)
        {
            bool isValid = false;

            User user = LoadUser(username);
            if (user != null)
            {
                isValid = user.ComparePassword(password);
            }

            return isValid;
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            bool isChanged = false;

            User user = LoadUser(username);
            if (user != null && user.ComparePassword(oldPassword))
            {
                user.SetPassword(newPassword);
                user.Save();

                user.Session.CommitTransaction();
                isChanged = true;
            }

            return isChanged;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            return false;
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            bool isDeleted = false;

            User user = LoadUser(username);
            if (user != null)
            {
                user.Delete();
                user.Save();

                user.Session.CommitTransaction();

                isDeleted = true;
            }
            return isDeleted;
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return 5; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 5; }
        }

        public override int PasswordAttemptWindow
        {
            get { return 100; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Hashed; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return string.Empty; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            //user.ProviderUserKey;
        }
    }
}
